package org.glut.wechat.videochat.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.glut.wechat.videochat.service.RoomService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RoomServiceImpl implements RoomService {

    private final RedisTemplate<String, String> redisTemplate;

    // Redis键前缀
    private static final String ROOM_PREFIX = "webrtc:room:";
    private static final String USER_PREFIX = "webrtc:user:";

    public RoomServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 用户加入房间
     * @param roomId 房间ID
     * @param userId 用户ID
     */
    @Override
    public void joinRoom(String roomId, String userId) {
        // 添加null检查
        if (userId == null || roomId == null) {
            throw new IllegalArgumentException("用户ID和房间ID不能为空");
        }

        // 防止重复加入
        if (Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(ROOM_PREFIX + roomId, userId))) {
            log.debug("用户[{}]已在房间[{}]中", userId, roomId);
            return;
        }

        // Redis集合添加用户
        redisTemplate.opsForSet().add(ROOM_PREFIX + roomId, userId);
        // 记录用户所在房间
        redisTemplate.opsForValue().set(USER_PREFIX + userId, roomId);

        log.info("用户[{}]成功加入房间[{}]", userId, roomId);
    }

    /**
     * 用户离开房间
     * @param roomId 房间ID
     * @param userId 用户ID
     */
    @Override
    public void leaveRoom(String roomId, String userId) {
        // 从房间成员集合中移除用户
        redisTemplate.opsForSet().remove(ROOM_PREFIX + roomId, userId);
        // 删除用户房间记录
        redisTemplate.opsForValue().set(USER_PREFIX + userId, "default_room");  // 重置为default_room

        // 检查是否房间已空，如果是则删除房间
        Long remainingMembers = redisTemplate.opsForSet().size(ROOM_PREFIX + roomId);
        if (remainingMembers != null && remainingMembers == 0) {
            redisTemplate.delete(ROOM_PREFIX + roomId);
            log.info("房间[{}]已无成员，自动销毁", roomId);
        }
    }

    /**
     * 获取房间所有成员
     * @param roomId 房间ID
     * @return 成员ID集合
     */
    @Override
    public Set<String> getRoomMembers(String roomId) {
        return redisTemplate.opsForSet().members(ROOM_PREFIX + roomId);
    }

    /**
     * 获取用户目前所在的房间id
     * @param userId 用户id
     * @return 房间id
     */
    @Override
    public String getUserRoom(String userId) {
        return redisTemplate.opsForValue().get(USER_PREFIX + userId);
    }

    /**
     * 检查用户是否在房间中
     * @param roomId 房间ID
     * @param userId 用户ID
     * @return 是否在房间中
     */
    @Override
    public boolean isUserInRoom(String roomId, String userId) {
        Boolean isMember = redisTemplate.opsForSet().isMember(ROOM_PREFIX + roomId, userId);
        return Boolean.TRUE.equals(isMember);
    }
}
